package com.ddn.service.logistics.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.ddn.mapper.logistics.HqManagerMapper;
import com.ddn.mapper.logistics.dto.HqManagerExportyDto;
import com.ddn.mapper.logistics.dto.HqSpeNumTj;
import com.ddn.mapper.logistics.dto.Hqmnum;
import com.ddn.mapper.logistics.dto.HqmnumTj;
import com.ddn.model.logistics.HqManage;
import com.ddn.service.logistics.HqManagerService;
import com.ddn.util.StringUtil;
import com.ddn.util.ThreadPoolUtil;
import com.ddn.vo.PageBean;
import com.ddn.vo.R;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author zlp
 * @date 2022/8/28 12:54
 */
@Service
public class HqManagerServiceImpl implements HqManagerService {
    @Autowired
    private HqManagerMapper dao;


    @Override
    public R save(HqManage manage) {
        if (dao.save(manage) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public R delete(int id) {
        if (dao.delete(id) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public R update(HqManage manage) {
        if (dao.update(manage) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public PageBean pageByName(String name, int page, int limit) {
        if (StringUtil.isNotEmpty(name)) {
            name = "%" + name + "%";
        }
        int start = (page - 1) * limit;
        return new PageBean((int) dao.selectCount(name), dao.selectPage(name, start, limit));
    }

    @Override
    public List<HqManagerExportyDto> all() {
        return dao.all();
    }

    @Override
    public R delByIds(int[] ids) {
        if (dao.delByIds(ids) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public R upload(MultipartFile file) throws IOException {
        //1.接收文件， 获取文件内容
        //1.验证上传文件是否存在
        if (!file.isEmpty()) {
            //2.解析Excel -EasyExcel
            //2.解析Excel数据
            List<HqManage> list = EasyExcel.read(file.getInputStream(), HqManage.class, new ReadListener() {
                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                }
            }).sheet().doReadSync();
            if (dao.saveBatch(list) > 0) {
                return R.ok();
            }
        }
        return R.fail();
    }

    //海量数量导入
    //Poi 操作Excel,引起OOM内存溢出 ->EasyExcel 代替Poi
    //还是会报OOM 获取接口超时RT（Response Time） 数据量太大
    //线程池，原生
    //设计模式（单例模式-IoDH）+线程池+Mybatis批处理
    @Override
    public R upload2(MultipartFile file) throws IOException {
        //加入线程池，解决海量数据导入
        //1.获取上传的文件，校验
       if(!file.isEmpty()){
           EasyExcel.read(file.getInputStream(), HqManage.class, new ReadListener<HqManage>() {
               List<HqManage> list=new ArrayList<>();
               @Override
               public void invoke(HqManage manage, AnalysisContext analysisContext) {
                   list.add(manage);
                   //每个线程最多处理2000条
                   if(list.size()>=2000){
                       List l1=new ArrayList(list);
                       list.clear();
                       //加入到线程池
                       ThreadPoolUtil.getInstence().executor.execute(()->{
                           dao.saveBatch(l1);
                       });
                   }
               }

               @Override
               public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    ThreadPoolUtil.getInstence().executor.execute(()->{
                        dao.saveBatch(list);
                    });
               }
           }).doReadAll();
           //3.返回结果
           return R.ok();
       }
        return R.fail();
    }

    @Override
    public R numTj() {
        //1.查询数据
        List<Hqmnum> list = dao.selectNum();
        List<HqmnumTj> result = new ArrayList<>();
        //2.组装数据  JDk8新特性
        list.forEach(s -> {
            System.out.println("111" + s.getNum());
            result.add(new HqmnumTj(s.getName(), s.getNum()));
        });
        return R.ok(result);
    }

    @Override
    public R typeTj() {
    //查询数据
        List<HqSpeNumTj> list=dao.typeNum();
        //组装数据
        HashMap<String,List> map=new HashMap<>();
        List<String> spe=new ArrayList<>();
        List<Integer> num=new ArrayList<>();
        list.forEach(s->{
            spe.add(s.getSpecification());
            num.add(s.getNum());
        });
        map.put("spe",spe);
        map.put("num",num);
        return R.ok(map);
    }
}
